<template>
	<view>
		<cu-custom bgColor="bg-white" :isBack="true">
			<block slot="content">
				<text style="font-size: 32rpx;color: #333333;line-height: 24px;">{{targetUserName}}</text>
			</block>
			<block slot="right">
				<text class="cuIcon-more" @click="isMore=true" data-target="DrawerModalR" style="color: #333333;font-size: 48rpx;"></text>
			</block>
		</cu-custom>
		<view class="cu-modal drawer-modal justify-end" style="z-index: 400;" :class="isMore?'show':''" @click="isMore=false">
			<view class="cu-dialog" @tap.stop="" style="height:140rpx;width:100rpx;right:32rpx;" :style="[{top:CustomBar+'px'}]">
				<button type="default" style="width: 100%;font-size: 28rpx;">举报</button>
				<button type="default" @click="addBlack" style="width: 100%;font-size: 28rpx;">拉黑</button>
			</view>
		</view>
		<view class="cu-chat">
			<view v-for="(message, index) in messageList" :key="index">
				<view v-if="message.sendId == userId" class="cu-item self">
					<view class="main">
						<view class="content shadow">
							{{message.context}}
						</view>
					</view>
					<view class="cu-avatar radius"
						style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big107000.jpg);">
					</view>
					<view class="date">13:23</view>
				</view>
				<view v-if="message.sendId != userId" class="cu-item">
					<view class="cu-avatar radius"
						style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big143004.jpg);">
					</view>
					<view class="main">
						<view class="content shadow">
							{{message.context}}
						</view>
					</view>
					<view class="date">13:23</view>
				</view>
			</view>
		</view>

		<view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
			<!-- <view class="action">
				<text class="cuIcon-sound text-grey"></text>
			</view> -->
			<input class="solid-bottom" v-model="inputText" :adjust-position="false" :focus="isFocus" maxlength="300"
				cursor-spacing="10" @keydown.enter="websocketSend()" @focus="InputFocus" @blur="InputBlur"></input>
			<!-- <view class="action">
				<text class="cuIcon-emojifill text-grey"></text>
			</view> -->
			<button @click="websocketSend()" class="cu-btn bg-green shadow">发送</button>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				InputBottom: 0,
				isFocus: false,
				isMore: false,
				CustomBar: this.CustomBar,

				targetUserId: this.$Route.query.targetUserId ? this.$Route.query.targetUserId : '1',
				targetUserName: this.$Route.query.targetUserName ? this.$Route.query.targetUserName : '马发宇',
				targetAvatar: this.$Route.query.targetAvatar ? this.$Route.query.targetAvatar : 'https://ossweb-img.qq.com/images/lol/web201310/skin/big81005.jpg',
				messageList: [],
				inputText: '',
				userId: this.$store.getters.userid,
				avatar: this.$store.getters.avatar,
			};
		},
		onLoad() {
			this.initWebSocket();
		},
		onUnload() {
			console.log("onUnload")
			this.closeSocket();
		},
		methods: {
			InputFocus(e) {
				this.InputBottom = e.detail.height
			},
			InputBlur(e) {
				this.InputBottom = 0    
			},
			initWebSocket: function() {
				// WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
				var userId = this.$store.getters.userid;
				// var url = this.$config.apiUrl.replace("https://","wss://").replace("http://","ws://")+"/test/"+userId;
				var url = this.$config.apiUrl.replace("https://", "wss://").replace("http://", "ws://") +
					"/ucenter/test/oneToOne/" + this.userId;
				console.log('私信：websocket url>>' + url);
				this.websock = new WebSocket(url);
				this.websock.onopen = this.websocketOnopen;
				this.websock.onerror = this.websocketOnerror;
				this.websock.onmessage = this.websocketOnmessage;
				this.websock.onclose = this.websocketOnclose;
			},
			websocketOnopen: function() {
				console.log("私信：WebSocket连接成功");
			},
			websocketOnerror: function() {
				console.log("私信：WebSocket连接发生错误");
				this.reconnect();
			},
			websocketOnmessage: function(e) {
				let data = JSON.parse(e.data);
				this.messageList.push(data);
				// console.log("私信：-----接收消息-------", e.data);
				// var data = eval("(" + e.data + ")"); //解析对象
			},
			websocketOnclose: function(e) {
				console.log("私信：connection closed (" + e.code + ")");
				// this.reconnect();
			},
			websocketSend() { // 数据发送
				if(this.inputText == '') {
					this.$tip.toast("不允许发送空白信息");
					this.isFocus = true;
					return;
				}
				try {
					let datetime = this.format(new Date(), "yyyy-MM-dd hh:mm:ss")
					const sendData = {
						sendId: this.userId,
						receiveId: this.targetUserId,
						context: this.inputText,
						type: 0,
					};
					this.websock.send(JSON.stringify(sendData));
					this.messageList.push(sendData);
					this.inputText = "";
					this.$tip.success("发送成功！");
				} catch (err) {
					console.log("私信：send failed (" + err.code + ")");
				}
			},
			reconnect() {
				var that = this;
				if (that.lockReconnect) return;
				that.lockReconnect = true;
				//没连接上会一直重连，设置延迟避免请求过多
				setTimeout(function() {
					console.info("私信：尝试重连...");
					this.initWebSocket();
					that.lockReconnect = false;
				}, 5000);
			},
			// 关闭websocket
			closeSocket() {
				this.websock.close();
				console.log("websocket关闭成功")
			},
			// todo 与后端联调
			addBlack() {
				this.$tip.confirm("确认要拉黑该用户吗？", true).then(()=> {
					this.$http.post('/ucenter/black/addBlack', {
						blackId: this.targetUserId,
						userId: this.userId
					}).then(res=>{
						const data = res.data;
						if(data.success) {
							this.$tip.success("拉黑成功！");
							uni.navigateBack({
								delta: 1
							})
						}
					})
				})
			},
			format(date, fmt) {	//格式化 Date -> string
				var o = {
					"M+": date.getMonth() + 1, //月份
					"d+": date.getDate(), //日
					"h+": date.getHours(), //小时
					"m+": date.getMinutes(), //分
					"s+": date.getSeconds(), //秒
					"q+": Math.floor((date.getMonth() + 3) / 3), //季度
					"S": date.getMilliseconds() //毫秒
				};
				if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
				for (var k in o)
				if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
				return fmt;
			}
		}
	}
</script>

<style>
	page {
		padding-bottom: 100upx;
	}
</style>
